package cn.com.sina.alan.oauth.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * test oauth2.0 api
 */
@Controller
public class TestCtr {

    private static final Logger log = LoggerFactory.getLogger(TestCtr.class);

    @RequestMapping("/")
    public String root() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/api/index")
    public String index(HttpServletRequest request) {
        return "index";
    }

    @RequestMapping(value = "/user/info")
    public Map getUserInfo() {
        Map user = new HashMap<>();
        user.put("id", "1001");
        user.put("name", "张三");
        user.put("image", "http://xxx.com/abc.jpg");

        return user;
    }

    @RequestMapping("/test/user")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public String testUser() {
        return "has USER securityed.";
    }

    @RequestMapping("/test/admin")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @ResponseBody
    public String testAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getName() + ">>>has ADMIN securityed.";
    }

}
